var param = {}, formId = 'queryForm', url = "/openx/order/queryService/listOrder", orderDetail = {};

var days = 30;
var intervalDays = 7;

var coupon = '';

(function () {
    $("#cityStore").yfCityStore({
        url: ecp_boss_server + '/openx/wms/cityStoreService/listCityStoreTree',
        filter: 'leaves'
    });
})();

//查询按钮触发
$.openx.query = function () {
    //查询验证时间区间
    var createStartTime = new Date($("#createStartTime").val().replace(/\-/g, "\/"));
    var createEndTime = new Date($("#createEndTime").val().replace(/\-/g, "\/"));
    if (createStartTime > createEndTime) {
        layer.msg('开始时间不能大于结束时间！');
        return false;
    }
    var orderCode = $("input[name='orderCode']").val();
    var parentOrderCode = $("input[name='parentOrderCode']").val();
    var outTradeCode = $("input[name='outTradeCode']").val();
    var receiverPhone = $("input[name='receiverPhone']").val();
    var waybillId = $("input[name='waybillId']").val();
    if (orderCode.trim() === '' && parentOrderCode.trim() === '' && outTradeCode.trim() === '' && receiverPhone.trim() === '' && waybillId.trim() === '') {
        if (isNaN(createStartTime.getTime())) {
            layer.msg('开始时间不能为空！');
            return false;
        }
        if (isNaN(createEndTime.getTime())) {
            layer.msg('结束时间不能为空！');
            return false;
        }
        if (createStartTime.setDate(createStartTime.getDate() + intervalDays) < createEndTime) {
            layer.msg('选择的时间区间必须在' + intervalDays + '天以内');
            return false;
        }
    }
    if(receiverPhone){
        if(receiverPhone.length<3){
            layer.msg('至少输入三位手机号码');
            return false;
        }
    }
    var orderStaus = $("input[name='orderStatus']").val();
    if (orderStaus !== '') {
        //异常状态
        $("#deliveryStatus").val(orderStaus === 'DELIVERY_EXCEPTION' && orderStaus !== 'ALL' ? orderStaus : '');

        //待下账
        $("#postingStatus").val(orderStaus === 'WAITING_POSTING' && orderStaus !== 'ALL' ? orderStaus : '');

        //退款中 和已退货
        $("#refundStatus").val((orderStaus === '2' || orderStaus === '1' || orderStaus === '0') && orderStaus !== 'ALL' ? orderStaus : '');

        //拣货超时
        $("#pickTimeOutStatus").val((orderStaus === 'PICK_TIME_OUT') ? orderStaus : '');

        if (orderStaus === 'DELIVERY_EXCEPTION' || orderStaus === 'WAITING_POSTING' || orderStaus === '2' || orderStaus === '1' || orderStaus === '0' || orderStaus === 'ALL' || orderStaus === 'PICK_TIME_OUT') {
            $("input[name='orderStatus']").val('');
        }

    }
    let channelCodes = [];
    try {
        let channels = $("#channelCode").yfChannel("getData");
        if (channels.length > 0) {
            channels.forEach(item => {
                channelCodes.push(item.displayChannel);
            })
        };
    }catch (e) {

    }
    let data = $.openx.getJsonObj(formId);
    data.channelCodes = channelCodes;
    if (orderStaus === 'PICK_TIME_OUT') {
        data.deliveryType = 'REAL_TIME';
    }
    data.channelCodes = channelCodes;
    param.order = data;
    var equryTimeStamp = new Date();
    $.openx.tableRefresh(url + "?t=" + equryTimeStamp.getTime(), param);
};

function topChannelChange(){
    setTimeout(function () {
        let channels = $('#topChannelCode').val();
        if(!channels){
            $("#channelCode").yfChannel("reset");
            $("#channelCode").attr("disabled", true);
            return;
        }
        let channelCodes = channels.split(',');
        if(channelCodes.length !== 1){
            $("#channelCode").yfChannel("reset");
            $("#channelCode").attr("disabled", true);
            return;
        }
        console.log('channelCodes',channelCodes);
        this.changeToChannelCode(channelCodes[0]);
    }, 100);
}
//初始化渠道树
async function changeToChannelCode(topChannelCode) {
    if (!topChannelCode) {
        layer.msg("请选择顶级渠道");
        return;
    }
    let options = {
        service: '/boss/channelService',
        method: "/listChannelTree",
        refreshMethod: "refreshChannelTree",
        importMethod: "importChannelCode",
        filter: 'leaves',
        topChannelCode: topChannelCode,
        isSearch: true,
        isImport: true,
    };
    $("#channelCode").yfChannel(options);
    $("#channelCode").attr("disabled", false);
}

//初始化时间
layui.use('laydate', function () {
    var laydate = layui.laydate;
    document.getElementById('createStartTime').value = laydate.now(-1) + ' 00:00:00';
    document.getElementById('createEndTime').value = laydate.now() + ' 23:59:59';

    var data = $.openx.getJsonObj(formId);

    if (data.createStartTime !== '') {
        data.createStartTime = data.createStartTime + " 00:00:00";
    }
    if (data.createEndTime !== '') {
        data.createEndTime = data.createEndTime + " 23:59:59";
    }
    data.storeCodes = [];
    param.order = data;
    $.openx.initTable("table", url, param);

});

function refreshthridReturnBtn() {
    var laydate = layui.laydate;
    var searchData = $.openx.getJsonObj(formId);
    if (searchData.createStartTime !== '') {
        searchData.createStartTime = searchData.createStartTime + " 00:00:00";
    } else {
        //searchData.createStartTime=laydate.now(-1) +" 00:00:00";
    }
    if (searchData.createEndTime !== '') {
        searchData.createEndTime = searchData.createEndTime + " 23:59:59";
    } else {
        //searchData.createEndTime=laydate.now()+" 23:59:59";
    }
    $X("/order/queryService", "countByStatus").callx({
        order: JSON.stringify(searchData), status: 0,
        onResult: function (result) {
            if (result > 0) {
                $(".thridReturnAppl").addClass("thridReturnApplCss");
            } else {
                $(".thridReturnAppl").removeClass("thridReturnApplCss");
            }
            setTimeout(refreshthridReturnBtn, 60 * 1000);
        },
        onError: function (error) {
            layer.msg('刷新三方退货申请失败！');
        }

    });
}


$(window).load(function () {
    refreshthridReturnBtn();
})

function resetForm() {
    $('#queryForm')[0].reset();
    $("#cityStore").yfCityStore("reset");
    $('#channelSelectsId').val(null).trigger('change');
    var laydate = layui.laydate;
    console.log(laydate.now().split(' ')[0]);
    document.getElementById('createStartTime').value = laydate.now(-1).split(' ')[0] + ' 00:00:00';
    document.getElementById('createEndTime').value = laydate.now().split(' ')[0] + ' 23:59:59';
    start.max = '2099-06-16';
    start.min = '1900-01-01';
    end.max = '2099-06-16';
    end.min = '1900-01-01';
    var storeCode = [];
    var storeList_data = $("#cityStore").yfCityStore("getData");
    if (storeList_data.length > 0) {
        $.each(storeList_data, function (i, item) {
            storeCode.push(item.displayStore);
        });
    }
    var data = $.openx.getJsonObj(formId);
    data.storeCodes = storeCode;
    data.createStartTime = data.createStartTime + " 00:00:00";
    data.createEndTime = data.createEndTime + " 23:59:59";
    param.order = data;
    $.openx.initTable("table", url + "?t=" + new Date().getTime(), param);
    //$.openx.query();
}


//查看订单详情
function showOrderDetail(row) {
    var html = $.openx.innerHtml('orderDetailTpl')
    $X("/order/queryService", "getOrderDetail").callx({
        orderCode: row.orderCode,
        onResult: function (result) {

            layer.closeAll('loading')
            result.coupon = false;
            result.channelName = channelMap.get(result.topChannelCode)
            var receiver = result.receiver
            result.createTime = $.openx.formatDate(new Date(result.createTime))
            if (receiver) {
                result.receiverName = receiver.name
                result.receiverPhone = receiver.phone
                result.address = (receiver.provinceName ? receiver.provinceName : "") + (receiver.cityName ? receiver.cityName : "") + (receiver.districtName ? receiver.districtName : "") + (receiver.detailAddress ? receiver.detailAddress : "")
            }

            //根据判断展示不同的按钮
            result.ActionButton = getOrderAction(result.state, result.payee, result.isRefund, result.deliveryProvider);

            //根据是否有售后单判断是否退货
            if (result.isRefund === 'N') {
                console.log(result.orderRefundList);
                if (result.orderRefundList != undefined && result.orderRefundList.length > 0) {
                    result.isRefund = 'Y';
                    result.ActionButton.applyRefund = false;
                    result.ActionButton.goodsRejecte = false;
                }
            }
            var additionalInfos = result.additionalInfos
            for (let i = 0; i < additionalInfos.length; i++) {
                if (additionalInfos[i].infoCode === 'couponSn'){
                    result.coupon = true;
                }
            }
            // if (result.parentOrderCode != undefined && (result.topChannelCode === 'PABC' || result.topChannelCode === 'PAHYS')) {
            //
            //     //检查是否显示查看处方单按钮
            //     var url = prescript_detail_url + result.parentOrderCode + ".pdf";
            //
            //     $.ajax({
            //         type: "GET",
            //         url: url,
            //         async: false,
            //         success: function (res) {
            //             result.ActionButton.showRecipeBtn = true;
            //         },
            //         error: function (res) {
            //             result.ActionButton.showRecipeBtn = false;
            //         }
            //     });
            // }

            laytpl($.openx.innerHtml('orderDetailTpl')).render(result, function (html) {
                $.openx.openLayer(null, '订单详情', html, true)
            });


            //当前订单详细对象
            orderDetail = result;
            console.log(result);
        },
        onError: function (error) {

        }
    });
}

//线下配送
function toOfflineDelivery(row) {
    $.openx.confirm('确定转线下配送吗？', function () {
        $X("/logistics/operateService", "autoOfflineFinish").callx({
            orderCode: row.orderCode,
            onResult: function (result) {
                layer.closeAll();
                $.openx.tableRefresh(null, null, true);
            },
            //请求失败执行
            onError: function (error) {
                layer.msg(JSON.parse(error).message);
            }
        });
    });
}

function changeOrderWMS() {
    $("#newWarehouseCode").css("display", "inline");
    $("#confirmChangeOrderWMS").show();
    $("#cancelChangeOrderWMS").show();
}

/**
 * 完善用户信息
 */
function fillingCustomerInfo() {

    var regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
    var regPhone1 = /^1\d{10}$/;
    var regPhone2 = /^([0-9]{3,4}-)?[0-9]{7,8}$/;
    var receiver = orderDetail.receiver || {};
    var additionalInfos = orderDetail.additionalInfos || [];
    receiver.remark = orderDetail.remark || '';
    if (additionalInfos.length > 0) {
        $.each(additionalInfos, function (index, val) {
            if (val.infoCode === 'idCard') {
                // infoValue
                if (regIdCard.test(val.infoValue)) {
                    receiver.idCard = val.infoValue;
                }
            }
        })
    }
    if (orderDetail.receiver.name == undefined || orderDetail.receiver.name === '' || orderDetail.receiver.name === '-') {
        receiver.name = '';
    }
    receiver.phoneTest = false;
    if (orderDetail.receiver.phone == undefined || orderDetail.receiver.phone === '' || orderDetail.receiver.phone === '-') {
        receiver.phone = '';
    } else {
        if (regPhone1.test(orderDetail.receiver.phone) || regPhone2.test(orderDetail.receiver.phone)) {
            receiver.phone = orderDetail.receiver.phone;
            receiver.phoneTest = true;
        } else if (orderDetail.receiver.phone.length > 0) {
            receiver.phone = orderDetail.receiver.phone;
        } else {
            receiver.phone = "";
        }
    }
    var html = $.openx.innerHtml('fillingCustomerInfoTpl');
    laytpl(html).render(receiver, function (renderHtml) {
        var fillingCustomerInfoTplIndex = $.openx.openLayer(['600', '330'], '完善信息', renderHtml, true, function () {
            var obj = $.openx.getJsonObj('fillingCustomerInfoForm');
            var info = {};
            if (obj != undefined) {
                if (obj.receiverName != undefined) {
                    if (obj.receiverName.length != 0 && obj.receiverName.trim().length < 1 && obj.receiverName.trim().length < 10) {
                        layer.tips("姓 名 填 写 错 误", '#receiverNameFill');
                        return;
                    }
                }
                if (obj.receiverPhone != undefined) {
                    if (regPhone1.test(obj.receiverPhone) || regPhone2.test(obj.receiverPhone)) {

                    } else if (obj.receiverPhone.length == 0) {

                    } else if (obj.receiverPhone === orderDetail.receiver.phone) {
                        obj.receiverPhone = '';
                    } else {
                        layer.tips("电 话 号 码 不 符 合 要 求", '#receiverPhoneFill');
                        return;
                    }
                }
                if (obj.receiverIdCard != undefined) {
                    if (regIdCard.test(obj.receiverIdCard)) {

                    } else if (obj.receiverIdCard.length == 0) {

                    } else {
                        layer.tips("身 份 证 号 码 不 符 合 要 求", '#receiverIdCardFill');
                        return;
                    }
                }
                if (((obj.receiverIdCard != undefined && obj.receiverIdCard.length == 0) || obj.receiverIdCard == undefined) &&
                    ((obj.receiverPhone != undefined && obj.receiverPhone.length == 0) || obj.receiverPhone == undefined) &&
                    ((obj.receiverName != undefined && obj.receiverName.length == 0) || obj.receiverName == undefined) &&
                    ((obj.receiverRemark != undefined && obj.receiverRemark.length == 0) || obj.receiverRemark == undefined)
                ) {
                    layer.msg("没有效值！");
                    // setTimeout(function () {
                    //     layer.closeAll()
                    // }, 1000);
                    return;
                }
                $X("/order/operateService", "updateCustomerInfo").callx({
                    orderCode: orderDetail.orderCode,
                    receiverName: obj.receiverName ? obj.receiverName : '',
                    receiverPhone: obj.receiverPhone ? obj.receiverPhone : '',
                    receiverIdCard: obj.receiverIdCard ? obj.receiverIdCard : '',
                    receiverRemark: obj.receiverRemark ? obj.receiverRemark : '',
                    onResult: function (result) {
                        if (result) {
                            layer.msg("修改成功")
                            setTimeout(function () {
                                layer.closeAll();
                                showOrderDetail(orderDetail);
                            }, 1000);

                        } else {
                            layer.msg("修改失败")
                        }
                    },
                    onError: function (error) {
                        layer.msg(JSON.parse(error).message);
                    }
                });
            }
        });
    });
}


function cancelChangeOrderWMS() {
    $("#newWarehouseCode").hide();
    $("#confirmChangeOrderWMS").hide();
    $("#cancelChangeOrderWMS").hide();
}

function confirmChangeOrderWMS(orderCode) {
    console.log(orderCode + $("#newWarehouseCode").val());
    var newWarehouseCode = $("#newWarehouseCode").val();
    if (newWarehouseCode.length == 0 || newWarehouseCode.trim() == '') {
        layer.msg("请输入仓库编码");
        return;
    }
    $X("/order/operateService", "changeOrderWMS").callx({
        orderCode: orderCode,
        newWarehouseCode: newWarehouseCode,
        onResult: function (result) {
            console.log(result);
            cancelChangeOrderWMS();
            layer.confirm('换仓操作已完成，是否回到列表？', {
                btn: ['好的', '停留在当前页面'] //按钮
            }, function () {
                layer.closeAll();
            }, function () {
            });
            $.openx.tableRefresh(null, null, true);
        },
        //请求失败执行
        onError: function (error) {
            layer.msg(JSON.parse(error).message);
        }
    });
}


/**
 * 退货入库按钮确认操作
 */
function refundOrderStockConfirm(orderCode) {
    $X("/order/queryService", "getOrderRefundByOrderCode").callx({
        orderCode: orderCode,
        onResult: function (result) {
            layer.closeAll('loading');
            orderDetail.refundOrder = result;
            var html = $.openx.innerHtml('returnOrderFinal');
            laytpl($.openx.innerHtml('returnOrderFinal')).render(orderDetail, function (html) {
                var index = $.openx.openLayer(['940', '530'], '确认退货申请', html, true, function () {
                    //确认操作
                    layer.confirm('请确认物品完好，是否退货入库？', {
                        btn: ['确认', '取消'] //按钮
                    }, function () {
                        doRefundOrderStock(orderCode);
                    }, function () {
                        layer.closeAll('loading');
                    });
                });
            });
        },
        //请求失败执行
        onError: function (error) {
            layer.msg(JSON.parse(error).message);
        }
    });
}

/**
 * 退运费按钮操作
 * @param orderCode
 */
function refundFreightConfirm(orderCode) {
    //确认操作
    layer.confirm('退运费后，本订单将不再支持退货，请确认是否操作？', {
        btn: ['确认', '取消'] //按钮
    }, function () {
        $X("/order/operateService", "refundFreight").callx({
            orderCode: orderCode,
            onResult: function (result) {
                layer.closeAll();
                $.openx.tableRefresh(null, null, true);
            },
            //请求失败执行
            onError: function (error) {
                layer.msg(JSON.parse(error).message);
            }
        });
    }, function () {
        layer.closeAll('loading');
    });
}


/*function manualRefund(orderCode) {
    layer.confirm('确定要退款吗？,退款后不支持撤销！', {
        btn: ['确认', '取消'] //按钮
    }, function () {
        $X("/order/operateService", "manualRefund").callx({
            orderCode: orderCode,
            onResult: function (result) {
                layer.closeAll();
                $.openx.tableRefresh(null, null, true);
            },
            //请求失败执行
            onError: function (error) {
                layer.msg(JSON.parse(error).message);
            }
        });
    }, function () {
        layer.closeAll('loading');
    });
}*/


/**
 * 三方退货申请-拒绝
 * @param orderCode
 */
function refuseReturn(orderCode) {
    thridReturnApplDeal(orderCode, "REFUSE_RETURN");
}

/**
 * 三方退货申请-同意直接退款
 * @param orderCode
 */
function agreeDirect(orderCode) {
    thridReturnApplDeal(orderCode, "AGREE_DIRECT");
}

/**
 * 三方退货申请-同意需退货
 * @param orderCode
 */
function agreeButRefund(orderCode) {
    thridReturnApplDeal(orderCode, "AGREE_BUT_REFUND");
}

/**
 * 三方退货申请处理
 * @param orderCode 订单编号
 * @param dealCode 处理编码 1-拒绝 2-同意直接退款 3-同意需退货
 */
function thridReturnApplDeal(orderCode, dealCode) {
    $X("/order/operateService", "thridReturnApplDeal").callx({
        orderCode: orderCode, dealCode: dealCode,
        onResult: function (result) {
            if (result) {
                //刷新按钮
                refreshthridReturnBtn();
                layer.closeAll();
                $.openx.tableRefresh(null, null, true);
            } else {
                layer.msg("操作失败");
            }
        },
        onError: function (error) {
            layer.msg("操作失败" + JSON.parse(error).message);
        }
    });
}


function doRefundOrderStock(orderCode) {
    $X("/order/operateService", "refundOrderStorage").callx({
        orderCode: orderCode,
        onResult: function (result) {
            layer.msg('退货单处理成功', {time: 1000}, function () {
                layer.closeAll();
                //手动刷新表格
                $.openx.tableRefresh(null, null, true);
            });
        },
        onError: function (error) {
            layer.msg(JSON.parse(error).message);
        }
    });
}


//取消订单
function orderCancel(orderCode) {
    var operatorId = null;
    var ls = window.localStorage;
    if (ls) {
        var v = ls.getItem("_openx_header");
        if (v) {
            var openx_header = JSON.parse(v);
            if (openx_header) {
                operatorId = openx_header.userCode
            }
        }
    }

    $.openx.confirm('确认取消订单？', function () {
        $X("/order/operateService", "cancelOrder").callx({
            orderCode: orderCode,
            operatorId: operatorId ? operatorId : "",
            remark: operatorId + "在运营平台取消订单操作",
            onResult: function (result) {
                layer.msg('取消订单成功');
                $.openx.tableRefresh(null, null, true);
                layer.closeAll()
            },
            onError: function (error) {
                layer.msg('取消订单失败');
            }
        });
    })
}


//申请退货的确认页面
function returnOrderconfirm() {
    var html = $.openx.innerHtml('returnOrderTpl');
    laytpl($.openx.innerHtml('returnOrderTpl')).render(orderDetail, function (html) {
        var index = $.openx.openLayer(['930', '630'], '退货', html, true, function () {
            //校验数据
            var params = {};
            if (!validateReturnForm(params)) {
                return false;
            }

            //拼装退货商品数据
            var array = [];
            var rebate = false;
            var refundOrderStatus = $("#refundOrderStatus").text();
            if (orderDetail.orderRefundList && orderDetail.orderRefundList.length > 0) {
                rebate = true;
            }
            $("#goodsInfo").find("tbody tr[id='goodsTr']").each(
                function (i, item) {
                    if (Number($(item).find("td").eq(9).find("select[id='quantitySelect']").val()) < Number($(item).find("td").eq(7).text())) {
                        rebate = true;
                    }

                    var goods = new Object();
                    /**当前行批号*/
                    var td = $(item).find("td");
                    /**商品编码*/
                    goods.goodsCode = $(td).eq(1).text();
                    /**商品执行价 */
                    goods.exercisePrice = $(td).eq(5).text();
                    /**记账价 */
                    goods.accountPrice = $(td).eq(6).text();
                    /**商品数量*/
                    var quantitySlt = $(td).eq(9).find("select[id='quantitySelect']").val();

                    goods.quantity = quantitySlt == undefined ? $(td).eq(9).text() : quantitySlt;
                    // goods.flag = false;
                    goods.gift = $(td).eq(11).text();
                    if (goods.quantity > 0) {
                        array.push(goods);
                    }
                    /**定位错误信息位置*/
                    $(td).eq(0).attr("class", "tips" + goods.goodsCode);
                });

            if (rebate) {
                var form = new Object();
                form.orderCode = params.orderCode;
                form.returnFreight = params.returnFreight;
                form.reason = params.reason;
                form.goods = array;
                form.totalAmount = $('#pct').text();
                form.deliveryAmount = $('#deliveryAmount').text();
                form.refundOrderStatus = refundOrderStatus;
                if (form.totalAmount == "0") {
                    layer.tips('请选择拒收或退货的商品', '#goodsInfo', {
                        tips: [2, '#ff4400']
                    });
                    return false;
                }
                //发起退货申请
                $X("/order/operateService", "rebateOrder").callx({
                    form,
                    onResult: function (result) {
                        layer.msg('退货单申请成功', {time: 1000}, function () {
                            layer.closeAll();
                            //手动刷新表格
                            $.openx.tableRefresh(null, null, true);
                        });
                    },
                    onError: function (error) {
                        error = JSON.parse(error);
                        layer.alert(error.message);
                    }
                });
            } else {
                if (refundOrderStatus == "ORDER_FINISH") {
                    $X("/order/operateService", "refundOrder").callx({
                        orderCode: params.orderCode,
                        returnFreight: params.returnFreight,
                        reason: params.reason,
                        onResult: function (result) {
                            layer.msg('退货单申请成功', {time: 1000}, function () {
                                layer.closeAll();
                                //手动刷新表格
                                $.openx.tableRefresh(null, null, true);
                            });
                        },
                        onError: function (error) {
                            error = JSON.parse(error);
                            layer.alert(error.message);
                        }
                    });
                } else if (refundOrderStatus == "RECEIVE_WAITING") {
                    applyRejectFullGoodsOfOrder(params.orderCode, params.returnFreight, params.reason);
                }
            }
        });
    });
    $('#refundReason').change(function () {
        var $reject = $("#refundGoodsReason");
        var $other = $("#customerReturnReason");
        if ($("#otherReason").is(":checked")) {
            $("#customerReturnReason").attr("disabled", false);
            if ($other.val() != "") {
                $reject.val($("#otherReason").val() + $("#customerReturnReason").val());
            } else {
                $reject.val("");
            }
        } else {
            $("#customerReturnReason").attr("disabled", true);
            $reject.val($(this).val());
        }
    });
}

function changePrice(row, parent) {
    var exerciseSinglePrice = parent.previousElementSibling.previousElementSibling.previousElementSibling.textContent;
    var accountSinglePrice = parent.previousElementSibling.previousElementSibling.textContent;

    parent.nextElementSibling.textContent = exerciseSinglePrice * row.value;

    var totalAmount = 0;
    $("#goodsInfo").find("tbody tr[id='goodsTr']").each(
        function (i, item) {
            var goods = new Object();
            /**当前行批号*/
            var td = $(item).find("td");
            totalAmount = (totalAmount * 1000 + Number($(td).eq(10).text() * 1000)) / 1000;
        });
    $("#pct").text(totalAmount);
}

// //商品拒收页面
// function rejectGoods(orderCode) {
//     laytpl($.openx.innerHtml('rejectGoodsTpl')).render({}, function (html) {
//         $.openx.openLayer(['500','450'], "商品拒收处理", html, true, function () {
//             var $reject = $("input[name='rejectGoodsReson']");
//             if ($reject.val() != "" && $reject.val() != $("#otherReson").val()) {
//                 // if (orderInfo.freightAmount && orderInfo.freightAmount > 0) {
//                 //     layer.confirm("是否退运费？<br/>运费金额：" + orderInfo.freightAmount + "元", {btn: ['是，退运费', '否，不退运费']},
//                 //             function () {
//                 //                 applyRejectFullGoodsOfOrder(orderCode, $reject.val(), true)
//                 //             },
//                 //             function () {
//                 //                 applyRejectFullGoodsOfOrder(orderCode, $reject.val(), false)
//                 //             });
//                 // } else {
//                     applyRejectFullGoodsOfOrder(orderCode, $reject.val())
//                 // }
//             } else {
//                 layer.msg("请选择原因");
//             }
//             return false;
//         });
//         //控制单选按钮
//         $(".i-checks").iCheck({radioClass: "iradio_square-green"});
//         $('input[type="radio"][name="refundReson"]').on('ifChecked', function () {

//             var $other = $("input[name='otherResonContent']");

//             var $reject = $("input[name='rejectGoodsReson']");

//             if ($(this).attr("id")) {
//                 $("input[name='otherResonContent']").attr("disabled", false);
//                 if ($other.val() != "") {
//                     $reject.val($(this).val() + $other.val());
//                 }
//             } else {
//                 $("input[name='otherResonContent']").attr("disabled", true);
//                 $reject.val($(this).val());
//             }
//         });
//     })
//     obj.goodsRejecte = false;
// }

function applyRejectFullGoodsOfOrder(orderCode, returnFreight, rejectinfo) {
    $X("/order/operateService", "rejectOrder").callx({
        orderCode: orderCode,
        returnFreight: returnFreight,
        reason: rejectinfo, //$reject.val(),
        onResult: function (data) {
            if (data) {
                layer.msg('操作成功', {time: 1000}, function () {
                    layer.closeAll();
                    //手动刷新表格
                    $.openx.tableRefresh(null, null, true);
                });
            } else {
                layer.msg("操作失败");
            }
        },
        //请求失败执行
        onError: function (error) {
            layer.msg("操作失败");
        }
    });
}

//校验表单数据
function validateReturnForm(params) {
    var refundGoodsReason = $("#refundGoodsReason").val();
    var returnFreight = $('input[name=isReturnFreight]:checked').val();
    params.orderCode = $('#returnOderCode').text();
    if (returnFreight && returnFreight.length > 0) {
        params.returnFreight = returnFreight;
    } else {
        layer.tips('请选择是否退运费', '#returnFreight_1', {
            tips: [2, '#ff4400']
        });
        return false;
    }
    if ($("#otherReason").is(":checked")) {
        if (!$('#customerReturnReason').val()) {
            layer.tips('请填写退货理由', '#customerReturnReason', {
                tips: [2, '#ff4400']
            });
            return false;
        }
    }
    if ($("#noneReason").is(":checked")) {
        layer.tips('请选择退货理由', '#refundReason', {
            tips: [2, '#ff4400']
        });
        return false;
    }
    if (refundGoodsReason && refundGoodsReason.length > 0 && refundGoodsReason.length < 256) {
        params.reason = refundGoodsReason;
    } else {
        if (refundGoodsReason.length <= 0) {
            layer.tips('请填写退货理由', '#customerReturnReason', {
                tips: [2, '#ff4400']
            });
        }
        if (refundGoodsReason.length > 256) {
            layer.tips('最多填写256个字符', '#customerReturnReason', {
                tips: [2, '#ff4400']
            });
        }
        return false;
    }
    return true;
}

//校验表单数据
function validateReturnForm1(params) {
    var returnReason = $('#returnReason').val();
    var returnFreight = $('input[name=isReturnFreight]:checked').val();
    params.orderCode = $('#returnOderCode').val();
    if (returnFreight && returnFreight.length > 0) {
        params.returnFreight = returnFreight;
    } else {
        layer.tips('请选择是否退运费', '#returnFreight_1', {
            tips: [2, '#ff4400']
        });
        return false;
    }
    if (returnReason && returnReason.length > 0 && returnReason.length < 256) {
        params.reason = returnReason;
    } else {
        if (returnReason.length <= 0) {
            layer.tips('请填写退货理由', '#returnReason', {
                tips: [2, '#ff4400']
            });
        }
        if (returnReason.length > 256) {
            layer.tips('最多填写256个字符', '#returnReason', {
                tips: [2, '#ff4400']
            });
        }
        return false;
    }
    return true;
}


//修改收货人地址信息
var openlayerIndex = 0;

function updateReceiverAdressDialogLayer() {
    var receiver = orderDetail.receiver || {}
    var html = $.openx.innerHtml('updateReceiverAdressTpl');
    laytpl(html).render(receiver, function (renderHtml) {
        openlayerIndex = $.openx.openLayer(null, '收货人地址修改', renderHtml, true, function () {
            var obj = $.openx.getJsonObj('updateReceiverAdressForm');

            //收货人信息
            var address = {}
            address.name = obj.receiverName
            address.phone = obj.receiverPhone
            address.provinceName = obj.receiverProvinceCode != '' ? $("#receiverProvinceCode option:selected").text() : "";
            address.cityName = obj.receiverCityCode != '' ? $("#receiverCityCode option:selected").text() : "";
            address.districtName = obj.receiverDistrictCode != '' ? $("#receiverDistrictCode option:selected").text() : "";
            address.provinceCode = obj.receiverProvinceCode != '' ? obj.receiverProvinceCode : "";
            address.cityCode = obj.receiverCityCode != '' ? obj.receiverCityCode : "";
            address.districtCode = obj.receiverDistrictCode != '' ? obj.receiverDistrictCode : "";
            address.detailAddress = obj.receiverAdress != '' ? obj.receiverAdress : "";

            $X("/order/operateService", "updateReceiverAdress").callx({
                orderCode: orderDetail.orderCode,
                receiver: address,
                onResult: function (result) {
                    if (result) {
                        layer.msg("修改成功")
                        setTimeout(function () {
                            layer.closeAll()
                        }, 1000);

                    } else {
                        layer.msg("修改失败")
                    }
                },
                onError: function (error) {

                }
            });
        });
    });
    initAreaSelect("receiverProvinceCode", "receiverCityCode", "receiverDistrictCode");
    //初始化省市区
    $('#receiverProvinceCode option').filter(function () {
        if ($(this).val() == receiver.provinceCode) {
            $("#receiverProvinceCode option[value='" + receiver.provinceCode + "']").attr("selected", true);
            $('#receiverProvinceCode').trigger("change");

            $("#receiverCityCode option[value='" + receiver.cityCode + "']").attr("selected", true);
            $('#receiverCityCode').trigger("change");

            $("#receiverDistrictCode option[value='" + receiver.districtCode + "']").attr("selected", true);
            return true;
        } else {
            return false
        }
    }).attr("selected", true);
}


//*****************格式化代码**********************/
//格式化下单时间
function createTimeFormat(value, row) {
    return $.openx.formatDate(new Date(value));
}

//格式化订单详情按钮
function showOrderDetailFormat(value, row) {
    var orderCode = row.orderCode.toString();
    var parentOrderCode = row.parentOrderCode.toString();
    var html = "<a href=\'javascript:void(0)\' onclick =\'javascript:showOrderDetail(" + JSON.stringify(row) + ")\'><button type='button' class='btn btn-outline btn-primary btn-xs'>订单详情</button> <a>";

    var offlineDelivery = (row.stateCode === 'DELIVERY_WAITING' || row.stateCode === 'RECEIVE_WAITING') && row.deliveryType !== 'SELF_PICK' && row.deliveryProvider !== 'DELIVERY_THIRD'
    if (offlineDelivery) {
        html += "<a href=\'javascript:void(0)\' onclick =\'javascript:toOfflineDelivery(" + JSON.stringify(row) + ")\'><button type='button' class='btn btn-outline btn-primary btn-xs'>线下配送</button> <a>"
    } else {
        html += "<a href=\'javascript:void(0)\'><button type='button' disabled  class='btn btn-outline btn-default btn-xs'>线下配送</button><a>";
    }
    return html;
}

function warehouseCodeFormatter(value, row) {
    if (value) {
        return "<a   style = '\color:#000000;text-decoration:underline;\' onclick='javascript:queryWarehouseDetail(" + JSON.stringify(row) + ");'><b>" + row.warehouseCode + "</b></a>";
    }
    return "-"

}

function remarkFormat(value, row) {
    if (row.remark) {
        if (row.remark.length > 10) {
            return "<a id='" + row.orderCode + "' onclick='showAll(" + JSON.stringify(row) + ");'>" + row.remark.substring(0, 10) + "\n..." + "</a>";
        } else {
            return row.remark;
        }
    }
    return "-";
}

function showAll(row) {
    layer.tips(row.remark, '#table a[id="' + row.orderCode + '"]', {
        tips: [4, '#78BA32'],
        area: ['auto', 'auto']
    });
}

function queryWarehouseDetail(row) {
    $X("/wms/physicalWMSService", "queryDetail").callx({
        warehouseCode: row.warehouseCode,
        onResult: function (data) {
            if (data) {
                if (data.status === 'CLOSE') {
                    data.status = '停业';
                } else if (data.status === 'OPEN') {
                    data.status = '营业';
                }
                if (data.type === 'SHOP') {
                    data.type = '门店';
                } else if (data.type === 'MAIN') {
                    data.type = '大仓';
                }
                var innerHtml = $.openx.innerHtml('warehouseDetail');
                laytpl(innerHtml).render(data, function (html) {
                    $.openx.openLayer(['auto', 'auto'], '查询仓库详情', html, true);
                });
            } else {
                layer.msg("无详情信息")
            }
        },
        onError: function (error) {
            var res = JSON.parse(error);
            layer.msg(res.message)
        }

    });
}


// 点击订单状态查询订单信息
var previousObj = $("button[name='orderStatus']")[0];
$("button[name='orderStatus']").on('click', function (e) {
    var $this = e.currentTarget;
    $("input[name='orderStatus']").val($this.value);
    if (previousObj != $this) {
        $($this).find('i').addClass("glyphicon glyphicon-ok-sign")
        $(previousObj).find('i').removeClass('glyphicon glyphicon-ok-sign');
    }
    previousObj = $this;
    $.openx.query();
})

function topChannelFormat(value, row) {
    return channelMap.get(value);
}

function queryLogistics() {
    $X("/logistics/logisticsListService", "listDeliveryTask").callx({
        orderCode: orderDetail.orderCode,
        onResult: function (result) {
            if (!result) {
                result = [{}];
            }
            layer.closeAll('loading')
            laytpl($.openx.innerHtml('logisticsInfotpl')).render(result, function (html) {
                $.openx.openLayer(null, '物流跟踪详情', html, true);
            });
        },
        onError: function (error) {
            var res = JSON.parse(error);
            layer.msg(res.message)
        }
    });
}

function formatCode(value, row) {
    if (value && value !== '000000') {
        return '\'' + value;
    } else {
        return '';
    }
}


function shipmentAgain(orderCode) {
    $.openx.confirm('是否确认重新出库操作？', function () {
        layer.closeAll('dialog');
        $X("/order/operateService", "shipmentAgain").callx({
            orderCode: orderCode,
            onResult: function (data) {
                if (data) {
                    layer.msg('操作成功', {time: 1000}, function () {
                        layer.closeAll();
                        //手动刷新表格
                        $.openx.tableRefresh(null, null, true);
                    });
                } else {
                    layer.msg("重新出库失败");
                }
            },
            //请求失败执行
            onError: function (error) {
                layer.msg("重新出库失败" + error.message);
            }
        });
    });

}


function showRecipe(topChannelCode) {
    // if (topChannelCode == undefined || topChannelCode == null || topChannelCode !== 'PAHYS' || topChannelCode !== 'PABC' || topChannelCode !== 'XRQEYS') {
    //     if (orderDetail.ordonnanceId != undefined) {
    //         var url = prescriptWebHtml + '?orderCode=' + orderDetail.parentOrderCode;
    //         layer.open({
    //             content: [url],
    //             type: 2,
    //             title: '查看处方',
    //             area: ['1000px', '500px']
    //         });
    //     }
    // }
    if (topChannelCode === 'PAHYS' || topChannelCode === 'PABC' || topChannelCode === 'DSJK' || topChannelCode === 'KWZY'|| topChannelCode === 'XLYG'
        || topChannelCode === 'NEB' || topChannelCode === 'FXJK' || topChannelCode === 'FXJKBC' || topChannelCode === 'CXKJ' || topChannelCode === 'ELEMEBC') {
        var url = prescript_detail_url + orderDetail.parentOrderCode + ".pdf";
        window.location.href = url;
    }else if(topChannelCode === 'JDDJ'  || topChannelCode === 'YYW'){
        var url = prescript_detail_url + orderDetail.parentOrderCode + ".jpg";
        window.location.href = url;
    } else if(topChannelCode === 'XRQEYS' || topChannelCode === 'XINGREN'){
        if (orderDetail.ordonnanceId != undefined) {
            var url = ecp_boss_logistics_tpl_url+"/html/order/prescriptionDetail.html?prescriptionId=" + orderDetail.ordonnanceId;
            loodPrescript(url);
        }
    } else if (topChannelCode === 'YFJX' || topChannelCode === 'ZHEBOTO' || topChannelCode === 'JDYJS' || topChannelCode === 'JDYJSBC'|| topChannelCode === 'YSQYJK' || topChannelCode === 'YSQYJKBC'|| topChannelCode === 'JKXB' || topChannelCode === 'YFYS' || topChannelCode === 'XR') {
        if (orderDetail.ordonnanceId !== undefined) {
            var url = prescription_boss_web_url + "/diagnostic/diagnostic-print.html?id=" + orderDetail.ordonnanceId;
            loodPrescript(url);
        }
    } else{
        //if(topChannelCode == undefined || topChannelCode == null){
        if (orderDetail.ordonnanceId != undefined) {
            // var url = prescriptWebHtml + '?orderCode=' + orderDetail.parentOrderCode;
            var url = prescription_boss_web_url + "/diagnostic/diagnostic-print.html?id=" + orderDetail.ordonnanceId;
            loodPrescript(url);
        }
        //}
    }
}

function loodPrescript(url){
    layer.open({
        content: [url],
        type: 2,
        title: '查看处方',
        area: ['1000px', '500px']
    });
}


function showServiceDispose(row) {
    console.log(row);
    var html = $.openx.innerHtml('serviceDisposeTpl')
    var orderCode = undefined == row ? orderDetail.orderCode : row.orderCode;
    var parentOrderCode = undefined == row ? orderDetail.parentOrderCode : row.parentOrderCode;

    $X("/order/queryService", "listOrderCsoLogByOrderCode").callx({
        orderCsoLog: {
            orderCode: orderCode,
            parent_order_code: parentOrderCode
        },
        onResult: function (result) {
            layer.closeAll('loading');
            var btnFlag = false;
            //orderDetail.orderCsoLogs=result;
            var orderCsoLogs = result.orderCsoLogs;
            for (var i = 0; i < orderCsoLogs.length; i++) {
                orderCsoLogs[i].operateTime = $.openx.formatDate(new Date(orderCsoLogs[i].operateTime));
            }
            if (result.orderCsoLogStatus == 2) {
                btnFlag = true;
            }
            laytpl($.openx.innerHtml('serviceDisposeTpl')).render(result, function (html) {

                //$.openx.openLayer(null, '客服处理记录', html, true);
                var options = {
                    content: html,
                    type: 1,
                    id: 'serviceDisposeDiv',
                    title: '客服处理记录',
                    area: ['800px', '500px']

                };
                $.extend(options, {
                    btn: ['再次标记', '取消'], yes: function (idnex) {
                        remarkPhaseServer(1, index, orderCode, parentOrderCode);
                        return false;
                    }, btn3: function (index, layero) {
                        //按钮【按钮三】的回调
                        layer.close(index);
                        //return false ;//开启该代码可禁止点击该按钮关闭
                    }
                });
                //判断是否需要有保存按钮
                if (!btnFlag) {
                    $.extend(options, {
                        btn: ['保存-已处理完成', '保存-仍需后续处理', '取消'], yes: function (idnex) {
                            saveOrderCsoLog(2, index, orderCode, parentOrderCode);
                            return false;
                        }
                        , btn2: function (index) {
                            saveOrderCsoLog(1, index, orderCode, parentOrderCode);
                            return false;
                        }
                        , btn3: function (index, layero) {
                            //按钮【按钮三】的回调
                            layer.close(index);
                            //return false ;//开启该代码可禁止点击该按钮关闭
                        }
                    });
                }
                var index = layer.open(options);
                //设置客服处理的高度，从而将按钮纳入弹出框
//             	var serviceDisposeDiv=$("#layui-layer"+index).find("#serviceDisposeDiv");
//             	var height=serviceDisposeDiv.css("height").substring(0,serviceDisposeDiv.css("height").length-2);
//            	serviceDisposeDiv.css("height",(height-40)+'px');
                //设置按钮的样式
                $("#layui-layer" + index).find(".layui-layer-btn1").addClass("layui-layer-btn0");
                $("#layui-layer" + index).find(".layui-layer-btn1").removeClass("layui-layer-btn1");
                if (btnFlag) {
                    $("#layui-layer" + index).find(".layui-layer-btn0").addClass("layui-layer-btn1");
                    $("#layui-layer" + index).find(".layui-layer-btn0").removeClass("layui-layer-btn0");
                }
//            	$("#layui-layer"+index).find(".layui-layer-btn1").css({"border-color":"yellow","background-color":"yellow","color":"blue"});
//            	$("#layui-layer"+index).find(".layui-layer-btn1 a").css(
//            			{"height": "28px","line-height": "28px","margin":"0 6px","padding":" 0 15px"
//            		,"border": "1px solid #dedede","background-color": "#f1f1f1",
//            		"color": "#333",
//            		"border-radius": "2px",
//            		"font-weight": "400",
//            		"cursor": "pointer",
//            		"text-decoration": "none"});
//            	$("#layui-layer"+index).find(".layui-layer-btn1").hover({"opacity": ".9","text-decoration": "none"});


            });


        },
        onError: function (error) {

        }
    });
}

function remarkPhaseServer(status, index, orderCode, parentOrderCode) {
    layer.confirm("是否打开再次标记？", function (confirmIndex) {
        $X("/order/operateService", "saveOrderCsoLog").callx({
            orderCsoLog: {
                parent_order_code: parentOrderCode,
                order_code: orderCode,
                result: "打开再次标记",
                status: status//,
            },
            onResult: function (data) {
                if (data) {
                    layer.msg('操作成功', {time: 1000}, function () {
                        layer.close(index);
                    });
                } else {
                    layer.msg("操作失败");
                }
            },
            //请求失败执行
            onError: function (error) {
                layer.msg("保存记录失败" + error.message);
            }
        });
        layer.close(confirmIndex);
    });


    return false;
}

function saveOrderCsoLog(status, index, orderCode, parentOrderCode) {
    var operateRemark = $("#operateRemark").val();
    if (operateRemark == "" || operateRemark == "undefined" || operateRemark == undefined) {
        layer.msg('客服处理说明不能为空！');
        return false;
    }
    if (typeof (operateRemark) == undefined || operateRemark.length > 500) {
        layer.msg('客服处理说明不能超过250个中文字符！');
        return false;
    }
    $X("/order/operateService", "saveOrderCsoLog").callx({
        orderCsoLog: {
            parent_order_code: parentOrderCode,
            order_code: orderCode,
            result: operateRemark,
            status: status//,
//			,operate_user_code:"123456",//用于未登陆直接使用
//			operate_user_name:"测试"//用于未登录直接使用
        },
        onResult: function (data) {
            if (data) {
                layer.msg('操作成功', {time: 1000}, function () {
                    layer.close(index);
                });
            } else {
                layer.msg("操作失败");
            }
        },
        //请求失败执行
        onError: function (error) {
            layer.msg("保存记录失败" + error.message);
        }
    });
    return false;
}

var start = {
    istime: true,
    format: 'YYYY-MM-DD hh:mm:ss',
    max: '2099-06-16',
    isclear: false,
    istoday: true,
    choose: function (datas) {
        end.min = datas; //开始日选好后，重置结束日的最小日期
        var date = new Date(datas.replace(/\-/g, "\/"));
        getDaysByMonth(date.getFullYear(), date.getMonth() + 1)
        date.setDate(new Date(date.getDate() + (days - 1)));
        end.max = DateToStr(date, 'max');

    }
};
var end = {
    istime: true,
    format: 'YYYY-MM-DD hh:mm:ss',
    max: '2099-06-16',
    isclear: false,
    istoday: true,
    choose: function (datas) {
        start.max = datas; //结束日选好后，重置开始日的最大日期
        var date = new Date(datas.replace(/\-/g, "\/"));
        getDaysByMonth(date.getFullYear(), date.getMonth());
        days = days > date.getDate() ? days : date.getDate();
        date.setDate(new Date(date.getDate() - (days - 1)));
        start.min = DateToStr(date, 'min');
    }
};

$("#createStartTime").on("click", function () {
    start.elem = this;
    laydate(start);
});
$("#createEndTime").on("click", function () {
    end.elem = this;
    laydate(end);
});

function DateToStr(date, flag) {
    var year = date.getFullYear();
    var month = (date.getMonth() + 1).toString();
    var day = (date.getDate()).toString();
    if (month.length == 1) {
        month = "0" + month;
    }
    if (day.length == 1) {
        day = "0" + day;
    }
//    var time='';
//    if(flag=='max'){time='23:59:59';}
//    if(flag=='min'){time='00:00:00';}
    dateTime = year + "-" + month + "-" + day;
    return dateTime;
}

//获取当前月多少天
function getDaysByMonth(year, month) {
    var monthDays;
    //判断月份大小获得天数
    if (month == '1' || month == '3' || month == '5' || month == '7' || month == '8' || month == '10' || month == '12') {
        monthDays = 31;
    } else if (month == '4' || month == '6' || month == '9' || month == '11') {
        monthDays = 30;
    } else {
        monthDays = 28;
        //判断当前选择的年份是否是闰年
        if ((year % 100 == 0 && year % 400 == 0) || year % 4 == 0) {
            monthDays = 29;
        }
    }
    days = monthDays;
    return days;
}

//乘法函数
function accMul(arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length;
    } catch (e) {
    }
    try {
        m += s2.split(".")[1].length;
    } catch (e) {
    }
    // alert(Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m));
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

